<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            .box {
                width: 100px;
                height: 100px;
                background-color: rebeccapurple;
                position: absolute;
                top: 0px;
                left: 100px;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
        <script>
            //获取元素
            let box = document.querySelector(".box");
            //使用event获取值，⚠️onkeydown获取按下的键盘
            document.onkeydown = (event) => {
                //获取据浏览器据左边的距离
                const offsetLeft = box.offsetLeft;
                console.log(offsetLeft);
                //获取据浏览器据顶部的距离
                const offsetTop = box.offsetTop;
                // 进行就判断修改属性
                if (event.key === "w") {
                    box.style.top = offsetTop - 2 + "px";//往上为-
                } else if (event.key === "s") {
                    box.style.top = offsetTop + 2 + "px";//反之
                } else if (event.key === "a") {
                    box.style.left = offsetLeft - 2 + "px";//往上为-
                } else if (event.key === "d") {
                    box.style.left = offsetLeft + 2 + "px";//反之
                }
            };
        </script>
    </body>
</html>
